{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.layui-table-body{max-height: 480px !important;}
	.layui-form-item .layui-input-inline.end-time{float: none;}
	.goods-title{display: flex;align-items: center;}
	.goods-title .goods-img{display: flex;align-items: center;justify-content: center;width: 55px;height: 55px;margin-right: 5px;}
	.goods-title .goods-img img{max-height: 100%;max-width: 100%;}
	.goods-title .goods-name{flex: 1;line-height: 1.6;}
</style>
{/block}
{block name="main"}
<div class="layui-collapse ns-tips">
	<div class="layui-colla-item">
		<h2 class="layui-colla-title">操作提示</h2>
		<ul class="layui-colla-content layui-show">
			<li>管理员可以在此页添加限时折扣活动</li>
			<li>活动时间不可与列表中的折扣活动时间冲突</li>
		</ul>
	</div>
</div>

<div class="layui-form ns-form">
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动名称：</label>
		<div class="layui-input-block">
			<input type="text" name="discount_name" lay-verify="required" autocomplete="off" class="layui-input ns-len-long">
		</div>
		<div class="ns-word-aux">
			<p>活动名称将显示在限时折扣活动列表中，方便商家管理使用</p>
		</div>
	</div>

	<div class="layui-form-item layui-form-text">
		<label class="layui-form-label">备注：</label>
		<div class="layui-input-block">
			<textarea name="remark" class="layui-textarea ns-len-long"></textarea>
		</div>
		<div class="ns-word-aux">
			<p>备注是商家对限时折扣活动的补充说明文字，在商品详情页-优惠信息位置显示；非必填选项</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动时间：</label>
		<div class="layui-inline">
			<div class="layui-input-inline">
				<input type="text" id="start_time" name="start_time" lay-verify="required" class="layui-input ns-len-mid" autocomplete="off" readonly>
				<i class="ns-calendar"></i>
			</div>
			<span class="layui-form-mid">-</span>
			<div class="layui-input-inline end-time">
				<input type="text" id="end_time" name="end_time" lay-verify="required|time" class="layui-input ns-len-mid" autocomplete="off" readonly>
				<i class="ns-calendar"></i>
			</div>
		</div>
	</div>

	<div class="layui-form-item goods_list">
		<label class="layui-form-label"><span class="required">*</span>商品选择：</label>
		<div class="layui-input-block">
			<table id="selected_goods_list" lay-filter="selected_goods_list"></table>
			<button class="layui-btn ns-bg-color" onclick="addGoods()">选择商品</button>
		</div>
	</div>

	<div class="ns-form-row">
		<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
	</div>
</div>

<!-- 操作 -->
<script type="text/html" id="operation">
	<div class="ns-table-btn">
		<a class="layui-btn" onclick="delGoods(this,{{d.sku_id}})">删除</a>
	</div>
</script>


<script type="text/html" id="discountPrice">
	<input type="number" class="layui-input ns-len-input discount_price" value="{{d.discount_price}}" onchange="setGoodsSku('discount_price', {{d.sku_id}}, this)" lay-verify="discount_price" min="0.00"/>
</script>

{/block}
{block name="script" }
<script type="text/html" id="toolbarOperation">
	<button class="layui-btn layui-btn-primary" lay-event="discount-price">折扣价</button>
</script>
<script>

	var goods_id = [], selectedGoodsId = [], sku_list = [];

	layui.use(['form', 'laydate'], function() {
		var form = layui.form,
			laydate = layui.laydate,
			repeat_flag = false, //防重复标识
			currentDate = new Date(),
			minDate = "";
		form.render();

		currentDate.setDate(currentDate.getDate() + 30);

		renderTable(sku_list); // 初始化表格

		laydate.render({
			elem: '#start_time', //指定元素
			type: 'datetime',
			value: new Date(),
			done: function(value) {
				minDate = value;
				reRender();
			}
		});

		//结束时间
		laydate.render({
			elem: '#end_time', //指定元素
			type: 'datetime',
			value: new Date(currentDate)
		});

		/**
		 * 重新渲染结束时间
		 * */
		function reRender() {
			$("#end_time").remove();
			$(".end-time").html('<input type="text" id="end_time" name="end_time" placeholder="请输入结束时间" lay-verify="required|time" class = "layui-input ns-len-mid" autocomplete="off"> ');
			laydate.render({
				elem: '#end_time',
				type: 'datetime',
				min: minDate
			});
		}

		/**
		 * 监听提交
		 */
		form.on('submit(save)', function(data) {

			var goods_data = [];

			for (var i in sku_list){
				var goods = {};
				goods.goods_id = sku_list[i]['goods_id'];
				if(goods_data.length == 0){
					goods_data.push(goods);
				}else {
					$.each(goods_data, function(index, event){
						if(goods_data.length == index+1 && event.goods_id != goods.goods_id){
							goods_data.push(goods);
						}
					})
				}
			}

			if(sku_list.length == 0){
				layer.msg('请选择商品', {icon: 5, anim: 6});
				return false;
			}

			$.each(goods_data, function (i, e) {
				goods_data[i]['sku_list'] = [];
				$.each(sku_list, function (index, event) {
					if(event.goods_id == e.goods_id) {
						goods_data[i]['sku_list'].push(event);
					}
				})
			})

			data.field.goods_data = goods_data;
			if (repeat_flag) return;
			repeat_flag = true;
			$.ajax({
				url: ns.url("discount://shop/discount/add"),
				data: data.field,
				dataType: 'JSON',
				type: 'POST',
				success: function(res) {
					repeat_flag = false;

					if (res.code == 0) {
						layer.confirm('添加成功', {
							title: '操作提示',
							btn: ['返回列表', '继续添加'],
							closeBtn: 0,
							yes: function() {
								location.href = ns.url("discount://shop/discount/lists")
							},
							btn2: function() {
								location.href = ns.url("discount://shop/discount/add");
							}
						});
					} else {
						layer.msg(res.message);
					}
				}
			});
		});

		/**
		 * 表单验证
		 */
		form.verify({
			time: function(value) {
				var now_time = (new Date()).getTime();
				var start_time = (new Date($("#start_time").val())).getTime();
				var end_time = (new Date(value)).getTime();
				if (now_time > end_time) {
					return '结束时间不能小于当前时间!'
				}
				if (start_time > end_time) {
					return '结束时间不能小于开始时间!';
				}
			},

			discount_price: function(value, item) {
				if (value == "" || value == 0) {
					return;
				}
				if (value < 0) {
					return '折扣金额不能小于0';
				}

			}
		});


	});


	function delGoods(obj,id) {
		var goods_ids = [];
		for (let i = 0; i < sku_list.length; i++){
			if (sku_list[i].sku_id == parseInt(id)){
				sku_list.splice(i,1);
			}
		}
		for (let i = 0; i < sku_list.length; i++){
			goods_ids.push(sku_list[i].goods_id);
		}
		$(obj).parents("tr").remove();
		selectedGoodsId = goods_ids.toString();
	}

	// 表格渲染
	function renderTable(sku_list) {
		//展示已知数据
		table = new Table({
			elem: '#selected_goods_list',
			page: false,
			limit: Number.MAX_VALUE,
			cols: [
				[{
					width: "3%",
					type: 'checkbox',
					unresize: 'false'
				},{
					field: 'sku_name',
					title: '商品名称',
					width: '23%',
					unresize: 'false',
					templet: function(data) {
						var html = '';
						html += `
							<div class="goods-title">
								<div class="goods-img">
									<img layer-src src="${data.sku_image ? ns.img(data.sku_image) : ''}" alt="">
								</div>
								<p class="ns-multi-line-hiding goods-name" data-goods_id="${data.goods_id}" data-sku_id="${data.sku_id}" title="${data.sku_name}">${data.sku_name}</p>
							</div>
						`;
						return html;
					}
				}, {
					field: 'price',
					title: '商品价格',
					unresize: 'false',
					align: 'left',
					width: '15%',
					templet: function(data) {
						return '<p class="ns-line-hiding" title="'+ data.price +'">￥<span>' + data.price +'</span></p>';
					}
				}, {
					field: 'stock',
					title: '库存',
					unresize: 'false',
					width: '10%',
					templet: function(data) {
						return '<p class="stock">' + data.stock +'</p>';
					}
				}, {
					title: '<span title="折扣价">折扣价<span>',
					unresize: 'false',
					width: '13%',
					templet: '#discountPrice'

				}, {
					title: '操作',
					toolbar: '#operation',
					width: '10%',
					unresize: 'false'
				}]
			],
			data: sku_list,
			toolbar: '#toolbarOperation'
		});
		/**
		 * 批量操作
		 */
		table.toolbar(function(obj) {

			if (obj.data.length < 1) {
				layer.msg('请选择要操作的数据');
				return;
			}
			switch (obj.event) {
				case "discount-price":
					editInput(0,obj);
					break;
			}
		});
	}

	function editInput(textIndex=0,data) {
		var text = [{
			name: '折扣价',
			value: 'discount_price'
		}];

		layer.open({
			type: 1,
			title:"修改"+text[textIndex].name,
			area:['600px'],
			btn:["保存","返回"],
			content: `
			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>${text[textIndex].name}：</label>
				<div class="layui-input-block">
					<input type="text" name="bargain_edit_input" lay-verify="required" autocomplete="off" class="layui-input ns-len-mid"  placeholder="请输入${text[textIndex].name}">
				</div>
			</div>
		`,
			yes: function(index, layero){
				var val = $("input[name='bargain_edit_input']").val();
				if (!val){
					layer.msg("请输入" + text[textIndex].name);
					return false;
				}
				data.data.forEach(function (item,index) {
					sku_list.forEach(function (skuItem,skuIndex) {
						if (item.sku_id == skuItem.sku_id){
							sku_list[skuIndex][text[textIndex].value] = val;
						}
					})
				});
				renderTable(sku_list);
				layer.closeAll();
			}
		});
	}

	/* 商品 */
	function addGoods(){

		goodsSelect(function (res) {
			if (!res.length) return false;
			for(var i=0;i<res.length;i++) {
				for (var k = 0; k < res[i].selected_sku_list.length; k++) {
					var item = res[i].selected_sku_list[k];
					item.discount_price = item.price;
					goods_id.push(item.goods_id);
					sku_list.push(item);
				}
			}
			renderTable(sku_list);
			selectedGoodsId = goods_id;


		}, selectedGoodsId);
	}

	function setGoodsSku(type, sku_id, obj){
		$.each(sku_list, function (i, e) {
			if(sku_id == e.sku_id){
				sku_list[i][type] = $(obj).val();
			}
		})
	}

	function back() {
		location.href = ns.url("discount://shop/discount/lists");
	}
</script>
{/block}